import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../lib_baseview.dart';
import '../../theme/jr.dart';
import '../gradient/jr_gradient_widget.dart';

///输入框
class JREditText extends StatefulWidget {
  final double height;
  final String? leftTitle;
  final Widget? leftChild;
  final Color borderColor;
  final VoidCallback? onLeftTap;
  final VoidCallback? onRightTap;
  final VoidCallback? onRandomTap;
  final String? initialValue;
  final ValueChanged<String>? onTextChanged;
  final String? hintText;
  final TextStyle? leftTitleStyle;
  final TextStyle? hintStyle;
  final TextStyle? textStyle;
  final TextInputType? keyboardType;
  final List<TextInputFormatter>? inputFormatters;
  final bool divider;
  final bool showRandom;
  final bool readOnly;
  final String? readOnlyText;
  final BorderRadius borderRadius;
  final double leftPadding;

  const JREditText({
    Key? key,
    this.leftTitle,
    this.leftChild,
    this.height = 44,
    this.borderColor = const Color(0xFFFAFAFA),
    this.onLeftTap,
    this.onRightTap,
    this.onRandomTap,
    this.initialValue,
    this.onTextChanged,
    this.leftTitleStyle,
    this.hintText,
    this.hintStyle = const TextStyle(
        fontSize: 14, fontWeight: FontWeight.w400, color: Color(0xFFD5D5D5)),
    this.textStyle = const TextStyle(
        fontSize: 14, fontWeight: FontWeight.w500, color: Color(0xFF333333)),
    this.keyboardType,
    this.inputFormatters,
    this.divider = true,
    this.readOnly = false,
    this.showRandom = false,
    this.readOnlyText,
    this.borderRadius = const BorderRadius.all(Radius.circular(22)),
    this.leftPadding = 15,
  }) : super(key: key);

  @override
  State<JREditText> createState() => JREditTextState();
}

class JREditTextState extends State<JREditText> {
  final _textControlor = TextEditingController();

  var _isDelVisible = false;

  setText(String str) {
    _textControlor.text = str;
    if (mounted) {
      setState(() {});
    }
  }

  @override
  void initState() {
    super.initState();
    _textControlor.text = widget.initialValue ?? "";
  }

  Widget get divider => widget.divider
      ? Padding(
          padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 15),
          child: Container(
            width: 1,
            height: 30,
            color: const Color(0xffD5D5D5).withOpacity(0.5),
          ),
        )
      : const Padding(
          padding: EdgeInsets.symmetric(horizontal: 15, vertical: 15),
        );

  @override
  Widget build(BuildContext context) {
    if (widget.readOnly &&
        widget.readOnlyText != null &&
        widget.readOnlyText!.isNotEmpty) {
      _textControlor.text = widget.readOnlyText!;
    }
    return Container(
      height: widget.height,
      decoration: BoxDecoration(
        border: Border.all(
          color: widget.borderColor,
        ),
        color: widget.borderColor,
        borderRadius: widget.borderRadius,
      ),
      child: Row(
        children: [
          SizedBox(
            width: widget.leftPadding,
          ),
          _leftChild(),
          divider,
          Expanded(
            child: Padding(
              padding: const EdgeInsets.only(bottom: 4),
              child: TextFormField(
                readOnly: widget.readOnly,
                onTap: widget.onRightTap,
                controller: _textControlor,
                onSaved: (newValue) {},
                onChanged: _onTextChanged,
                decoration: InputDecoration(
                  border: InputBorder.none,
                  hintText: widget.hintText,
                  hintStyle: widget.hintStyle,
                ),
                style: widget.textStyle,
                keyboardType: widget.keyboardType,
                inputFormatters: _getInputFormatters(),
              ),
            ),
          ),
          Visibility(
            visible: _isDelVisible,
            child: InkWell(
              onTap: _onDeleteClick,
              child: Container(
                alignment: Alignment.center,
                width: 35,
                height: widget.height,
                child: JR.img(
                  'common/common_close_icon.png',
                  width: 16,
                  height: 16,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _leftChild() {
    return InkWell(
      onTap: widget.onLeftTap,
      child: widget.leftChild ??
          Text(
            widget.leftTitle ?? "",
            style: widget.leftTitleStyle ??
                const TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w400,
                    color: Color(0xff999999)),
          ),
    );
  }

  _getInputFormatters() {
    List<TextInputFormatter> list = widget.inputFormatters ?? [];
    if (widget.keyboardType == TextInputType.phone ||
        widget.keyboardType == TextInputType.number) {
      list.add(FilteringTextInputFormatter(RegExp("[0-9.]"), allow: true));
    }
    if (widget.keyboardType == TextInputType.phone) {
      list.add(FilteringTextInputFormatter(RegExp("[0-9.]"), allow: true));
      list.add(LengthLimitingTextInputFormatter(11));
    }
    return list;
  }

  void _onDeleteClick() {
    setState(() {
      _textControlor.text = "";
      _onTextChanged('');
      _isDelVisible = false;
    });
  }

  void _onTextChanged(String value) {
    if (value.isNotEmpty) {
      if (!_isDelVisible) {
        setState(() {
          _isDelVisible = true;
        });
      }
    } else {
      setState(() {
        _isDelVisible = false;
      });
    }
    widget.onTextChanged?.call(value);
  }
}

///通用按鈕
class JRButton extends StatelessWidget {
  final double? width, height;
  final String? title;
  final bool enabled;
  final EdgeInsetsGeometry margin;
  final EdgeInsetsGeometry padding;
  final VoidCallback onPressed;
  final BorderRadius? borderRadius;
  final TextStyle? style;
  final List<Color>? colors;
  final Widget? child;

  const JRButton(
      {Key? key,
      this.width = double.infinity,
      this.height = 48,
      required this.title,
      required this.onPressed,
      this.margin = const EdgeInsets.symmetric(vertical: 0, horizontal: 0),
      this.padding = const EdgeInsets.symmetric(vertical: 0, horizontal: 0),
      this.enabled = true,
      this.borderRadius,
      this.colors,
      this.style,
      this.child})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    List<Color> gradientColors = colors ?? JR.color.brandGradient;
    return GestureDetector(
      onTap: enabled ? onPressed : null,
      child: Container(
        margin: margin,
        child: JRGradientWidget(
          gradient: LinearGradient(
              colors: enabled
                  ? gradientColors
                  : gradientColors.map((e) => e.withOpacity(0.3)).toList(),
              begin: AlignmentDirectional.bottomStart,
              end: AlignmentDirectional.topEnd),
          child: Container(
            padding: padding,
            height: height,
            width: width,
            alignment: AlignmentDirectional.center,
            child: child ??
                Text(
                  title ?? "",
                  style: style ??
                      const TextStyle(
                          color: Colors.white,
                          fontSize: 16,
                          fontWeight: FontWeight.w500),
                  maxLines: 1,
                ),
          ),
        ),
      ),
    );
  }
}

///宽度根据文本自适应
class RTextButton extends StatelessWidget {
  final double? height;
  final String? title;
  final bool enabled;
  final EdgeInsetsGeometry margin;
  final EdgeInsetsGeometry padding;
  final VoidCallback onPressed;
  final BorderRadius? borderRadius;
  final TextStyle? style;

  const RTextButton({
    Key? key,
    this.height = 32,
    required this.title,
    required this.onPressed,
    this.margin = const EdgeInsets.symmetric(vertical: 0, horizontal: 0),
    this.padding = const EdgeInsets.symmetric(vertical: 0, horizontal: 12),
    this.enabled = true,
    this.borderRadius,
    this.style,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return JRButton(
      title: title,
      onPressed: onPressed,
      width: null,
      padding: padding,
      enabled: enabled,
      style: style ?? TextStyle(color: Colors.black),
      margin: margin,
      height: height,
    );
  }
}

// class RGradientBorderButton extends StatelessWidget {
//   final double height;
//   final String? title;
//   final double? width;
//   final bool enabled;
//   final EdgeInsetsGeometry margin;
//   final EdgeInsetsGeometry padding;
//   final VoidCallback onPressed;
//   final TextStyle? style;

//   const RGradientBorderButton(
//       {Key? key,
//       this.height = 32,
//       required this.title,
//       required this.onPressed,
//       this.margin = const EdgeInsets.symmetric(vertical: 0, horizontal: 0),
//       this.padding = const EdgeInsets.symmetric(vertical: 0, horizontal: 0),
//       this.enabled = true,
//       this.style,
//       this.width})
//       : super(key: key);

//   @override
//   Widget build(BuildContext context) {
//     List<Color> gradientColors = JR.color.brandGradient;
//     return GradientBorder(
//       borderGradient: LinearGradient(colors: gradientColors),
//       borderWidth: 1,
//       borderRadius: height / 2.0,
//       child: GestureDetector(
//         onTap: enabled ? onPressed : null,
//         child: Container(
//           padding: padding,
//           margin: margin,
//           height: height,
//           width: width,
//           alignment: AlignmentDirectional.center,
//           child: JRGradientText(
//             title ?? "",
//             LinearGradient(colors: gradientColors),
//             style ??
//                 const TextStyle(
//                     color: Colors.white,
//                     fontSize: 16,
//                     fontWeight: FontWeight.w500),
//           ),
//         ),
//       ),
//     );
//   }
// }
